<?php


namespace PKApp\Form\Classes;


use PKApp\Model\Classes\OptionsService;
use PKApp\Model\Classes\TraitModel;
use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\Numbers;

trait TraitFrom
{
    use TraitModel;
    protected $id_form;
    protected $listId_option_field, $listField_option;

    protected function serviceForm(): FormService
    {
        static $cls;
        $this->id_form = Numbers::To(request()->get('formId'));
        !empty($cls) ?: $cls = new FormService($this->id_form);
        return $cls;
    }

    protected function getFieldByRestrict($value): array
    {
        $params = $this->modelOfToOutData()->Get(
            [$this->serviceForm()->restrictField => $value],
            $this->id_form, 'level');
        Arrays::Is($params) ?: $this->noticeByJson('Empty_restrictField');
        return [$this->serviceForm()->restrictField => $params[$this->serviceForm()->restrictField]];
    }

    protected function getFieldByOption()
    {
        $this->listField_option = $this->listId_option_field = [];
        $list_field = $this->serviceOfField()->GetList([
            'modelId' => $this->id_form, 'formType' => 'option'
        ], ['field', 'setting']);
        if (Arrays::Is($list_field)) {
            $id_option_parent = [];
            foreach ($list_field as $item_field) {
                $setting = Arrays::Unserialize($item_field['setting']);
                $id_option = Arrays::GetKey('option', $setting, 'ModelField_option_Empty', 'model');
                $id_option_parent[] = $id_option;
                $this->listId_option_field[$id_option] = $item_field['field'];
            }
            $service_option = new OptionsService();
            $list_option = $service_option->GetList(['parentId' => $id_option_parent]);
            if (Arrays::Is($list_option)) {
                foreach ($id_option_parent as $id_parent) {
                    $listTmp_option = array_filter($list_option, function ($item_option) use ($id_parent) {
                        return $item_option['parentId'] == $id_parent ? $item_option : [];
                    });
                    if (Arrays::Is($listTmp_option)) {
                        $listTmp_option = Arrays::Column($listTmp_option, 'name', 'id');
                    }
                    $this->listField_option[$this->listId_option_field[$id_parent]] = $listTmp_option;
                }
            }
        }
    }
}